﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameEngineer.Vertex;

namespace GameEngineer.BaseMatrix
{
    public class Matrix4X4 : BaseMatrix
    {
        public Matrix4X4()
        {
            this.mMatrix = new float[4, 4];
            this.mRow = 4;
            this.mColumn = 4;
        }

        //多个顶点的矩阵转换
        public Vertex4[] Mul(params Vertex4[] vertexs)
        {
            List< Vertex4> vertex4x4s = new List<Vertex4>();

            foreach (var vertex in vertexs)
            {
                if (Mul(vertex) != null)
                {
                    vertex4x4s.Add(Mul(vertex));
                }
            }

            return vertex4x4s.ToArray();
        }

        // 单个顶点的矩阵转换
        public Vertex4 Mul(Vertex4 vertex)
        {
            Vertex4 vertex4 = new Vertex4();

            if (this.mColumn == vertex.Width())
            {
                vertex4.mVertexX = this[0, 0] * vertex.mVertexX + this[1, 0] * vertex.mVertexY + this[2, 0] * vertex.mVertexZ + this[3, 0] * vertex.mVertexW;
                vertex4.mVertexY = this[0, 1] * vertex.mVertexX + this[1, 1] * vertex.mVertexY + this[2, 1] * vertex.mVertexZ + this[3, 1] * vertex.mVertexW;
                vertex4.mVertexZ = this[0, 2] * vertex.mVertexX + this[1, 2] * vertex.mVertexY + this[2, 2] * vertex.mVertexZ + this[3, 2] * vertex.mVertexW;
                vertex4.mVertexW = this[0, 3] * vertex.mVertexX + this[1, 3] * vertex.mVertexY + this[2, 3] * vertex.mVertexZ + this[3, 3] * vertex.mVertexW;

                return vertex4;
            }
            else
            {
                Console.WriteLine("顶点转化失败！");
                return null;
            }           
        }
        
        // 矩阵的转换
        public Matrix4X4 Mul(Matrix4X4 matrix)
        {
            Matrix4X4 matrix4x4 = new Matrix4X4();

            if (this.mColumn == matrix.mRow)
            {
                for (int x = 0; x < this.mRow; x++)
                {
                    for (int y = 0; y < matrix.mColumn; y++)
                    {
                        for (int z = 0; z < this.mColumn; z++)
                        {
                            matrix4x4[x, y] += this[x,z] * matrix[z,y];
                        }
                    }
                }

                return matrix4x4;
            }
            else
            {
                Console.WriteLine("矩阵转化失败！");
                return null;
            }
        }
    }
}
